import { checkOptions } from "../common";

interface IMapEvent {
  type: string;
  layerId?: string;
  listener: any;
}

export class MapEventController {
  private map: any;
  private mapEvents: Array<any> = [];
  constructor(options: any) {
    this.initOptions(options);
  }

  private initOptions(options: any) {
    const checkedOptions = checkOptions(options, [
      { key: "map", require: true },
    ]);
    this.map = checkedOptions.map;
  }

  private registerMapEvent(mapEvent: IMapEvent): void {
    if (mapEvent.layerId) {
      this.map.on(mapEvent.type, mapEvent.layerId, mapEvent.listener);
    } else {
      this.map.on(mapEvent.type, mapEvent.listener);
    }
    this.mapEvents.push(mapEvent);
  }

  private removeMapEvent(eventType: string, layerId: string): void {
    this.mapEvents.forEach((evt, index) => {
      if (evt.type === eventType && evt.layerId === layerId) {
        this.map.off(evt.type, evt.layerId, evt.listener);
        delete this.mapEvents[index];
      }
    });
  }

  /**
   * 清除地图的
   * @param eventType 
   * @param layerId 
   */
  private clearMapEvent(eventType: string, layerId?: string): void {
    this.mapEvents.forEach((evt, index) => {
      if (layerId && evt.type === eventType && evt.layerId === layerId) {
        this.map.off(evt.type, evt.layerId, evt.listener);
      } else {
        this.map.off(evt.type, evt.listener);
      }
      delete this.mapEvents[index];
    });
  }
}
